import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import {getPathById, getObjById} from './utils';
import * as api from './api';
import {uuid} from '../utils';
import moment from 'moment';
import {partsPriceType} from '../Enum';
/*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = data => ({
    type: GET_INIT_SUCCESS,
    data,
});
export const getInitDataFail = () => ({
    type: GET_INIT_FAIL,
});
export const getInitData = (code = PAGE_CODE) => dispatch => getCurrentUserPagePermissionsApi(code).then(res => {
    if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
    else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
    return res.isOk;
});

export const GET_CATEGORY_BEGIN = 'GET_CATEGORY_BEGIN';
export const GET_CATEGORY_SUCCESS = 'GET_CATEGORY_SUCCESS';
export const GET_CATEGORY_FAIL = 'GET_CATEGORY_FAIL';
export const getCategoryBegin = () => ({
    type: GET_CATEGORY_BEGIN
});

export const getCategorySuccess = (data, parentId) => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const path = getPathById(trees, parentId) || [];
    const newData = parentId ? data.map(item => {
        item.parentId = parentId;
        return item;
    }) : data;
    return dispatch({
        type: GET_CATEGORY_SUCCESS,
        data: newData,
        path
    });
};
export const getCategoryFail = () => ({
    type: GET_CATEGORY_FAIL,
});
export const getTopCategories = (forceRefresh = true) => (dispatch, getState) => {
    if(!forceRefresh) {
        const categories = getState().getIn(['page', 'domainData', 'categories', 'data']);
        if(categories && !categories.isEmpty())
            return Promise.resolve(true);
    }
    dispatch(getCategoryBegin());
    return api.getCategoriesTop().then(res => {
        if(res.ok) {
            const {content = []} = res.data;
            const data = content.map(item => ({
                items: [],
                ...item
            }));
            dispatch(getCategorySuccess(data || []));
        } else
            dispatch(getCategoryFail());
        return res.ok;
    });
};

export const getCategoryChildren = parentId => dispatch =>
    // dispatch(getCategoryBegin());
    api.getCategories(parentId).then(res => {
        if(res.ok) {
            const {content = []} = res.data;
            const data = content.map(item => ({
                items: [],
                ...item
            }));
            dispatch(getCategorySuccess(data, parentId));
        } else
            dispatch(getCategoryFail());
        return res.ok;
    })
    ;
/*==============================查询列表================================= */

export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition
});
export const getListFail = () => ({
    type: GET_LIST_FAIL,
}); //获取列表

export const getList = condition => dispatch => {
    dispatch(getListBegin());
    return api.getList(condition).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
        return res.ok;
    });
}; //按钮搜索

export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    dispatch(getList(condition));
}; //分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

export const categorySearch = id => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    condition.partCategoryId = id;
    return dispatch(getList(condition));
};

/*==============================查询列表================================= */

export const GET_ASSISTS_BEGIN = 'GET_ASSISTS_BEGIN';
export const GET_ASSISTS_SUCCESS = 'GET_ASSISTS_SUCCESS';
export const GET_ASSISTS_FAIL = 'GET_ASSISTS_FAIL';
export const getAssistsListBegin = () => ({
    type: GET_ASSISTS_BEGIN
});
export const getAssistsListSuccess = (data, condition) => ({
    type: GET_ASSISTS_SUCCESS,
    data,
    condition
});
export const getAssistsListFail = () => ({
    type: GET_ASSISTS_FAIL,
});
export const getAssists = condition => dispatch => {
    dispatch(getAssistsListBegin());
    return api.getAssists(condition).then(res => {
        if(res.ok)
            dispatch(getAssistsListSuccess(res.data.content, condition));
        else
            dispatch(getAssistsListFail());
        return res.ok;
    });
};

//重置查询条件

export const RESET_QUERY_ASSISTS_PANEL = 'RESET_QUERY_ASSISTS_PANEL';
export const resetQueryAssistsPanel = () => ({
    type: RESET_QUERY_ASSISTS_PANEL,
});
export const SAVE_QUERY_ASSISTS_CONDITION = 'SAVE_QUERY_ASSISTS_CONDITION';
export const saveQueryAssistsCondition = (name, value) => ({
    type: SAVE_QUERY_ASSISTS_CONDITION,
    name,
    value
});

export const tableAssistsSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryAssistsBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getAssists(condition));
};

//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
/*==============================新增维修项目分类================================ */

export const ADD_CATEGORY = 'ADD_CATEGORY';
export const onClickAddCategory = data => (dispatch, getState) => api.addCategory(data).then(res => {
    if(res.ok) {
        const {parentId, ...props} = data;
        const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
        const path = getPathById(trees, parentId) || [];
        dispatch({
            type: ADD_CATEGORY,
            path,
            data: {
                ...props,
                ...res.data,
                items: [],
                isNew: true
            }
        });
    }
    return res.ok;
});

/*==============================编辑维修项目分类================================ */
export const UPDATE_CATEGORY = 'UPDATE_CATEGORY';
export const updateCategory = (id, data) => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const path = getPathById(trees, id) || [];
    dispatch({
        type: UPDATE_CATEGORY,
        path,
        data
    });
};

export const onClickUpdateCategory = (data, id) => dispatch => {
    const {code, name, remark, rowVersion} = data;
    return api.updateCategory(id, {
        code,
        name,
        remark,
        rowVersion
    }).then(res => {
        if(res.ok)
            dispatch(updateCategory(id, {
                code,
                name,
                remark,
                ...res.data
            }));
        return res.ok;
    });
};

export const onSubmitCategory = (data, id) => dispatch => {
    if(id)
        return dispatch(onClickUpdateCategory(data, id));
    return dispatch(onClickAddCategory(data));
};
/*==============================停用维修项目分类================================ */
export const ABANDON_CATEGORY = 'ABANDON_CATEGORY';
export const abandonCategory = id => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const path = getPathById(trees, id) || [];
    dispatch({
        type: ABANDON_CATEGORY,
        path,
    });
};
export const onClickAbandonCategory = id => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const {rowVersion} = getObjById(trees, id) || {};
    return api.abandonCategory(id, {rowVersion}).then(res => {
        if(res.ok) {
            dispatch(abandonCategory(id));
            const {partCategoryId} = getState()
                .getIn(['page', 'appState', 'queryCondition'])
                .toJS() || {};
            if(partCategoryId && partCategoryId === id)
                return dispatch(categorySearch());
        }
        return res.ok;
    });
};
/*==============================编辑维修项目================================ */
export const onClickUpdateInfo = id => (dispatch, getState) => {
    const {partDutyUnits = [], partServicePrices = [], partServiceProperties = [], rowVersion, partCategoryId, tempPartServiceProperties = []} = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    const details = partDutyUnits.map(item => ({
        dutyUnitId: item.dutyUnitId,
        isDefault: Boolean(item.isDefault)
    }));
    const partServicePropertiesList = partServiceProperties.concat(tempPartServiceProperties);
    const brands = partServicePropertiesList.map(item => ({
        brandId: item.brandId,
        dealerId: item.dealerId,
        partWarrantyCategoryId: item.partWarrantyCategoryId,
        isPreAuthorized: item.isPreAuthorized,
        isNeedPicture: item.isNeedPicture,
    }));
    const prices = partServicePrices.map(item => ({
        brandId: item.brandId,
        currency: item.currency,
        price: item.price
    }));

    return api.updateInfo(id, {
        partDutyUnits: details,
        partServicePrices: prices,
        partServiceProperties: brands,
        rowVersion,
        partCategoryId
    });
};


export const SAVE_SUBMIT_CONDITION = 'SAVE_SUBMIT_CONDITION';
export const saveSubmitCondition = (name, value) => ({
    type: SAVE_SUBMIT_CONDITION,
    name,
    value
});
/* =======================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const GET_REPAIR_DETAIL_BEGIN = 'GET_REPAIR_DETAIL_BEGIN';
export const GET_REPAIR_DETAIL_SUCCESS = 'GET_REPAIR_DETAIL_SUCCESS';
export const GET_REPAIR_DETAIL_FAIL = 'GET_REPAIR_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN
});
export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data
});
export const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});
export const getDetail = (id, isUpdate) => dispatch => {
    dispatch(getDetailBegin());
    return api.getDetail(id, isUpdate).then(res => {
        if(res.ok)
            dispatch(getDetailSuccess(res.data));
        else
            dispatch(getDetailFail());
        return res.ok;
    });
};
// 辅料清单
export const getRepairDetailBegin = () => ({
    type: GET_REPAIR_DETAIL_BEGIN
});
export const getRepairDetailSuccess = data => ({
    type: GET_REPAIR_DETAIL_SUCCESS,
    data
});
export const getRepairDetailFail = () => ({
    type: GET_REPAIR_DETAIL_FAIL,
});
export const getRepairDetail = id => dispatch => {
    dispatch(getRepairDetailBegin());
    return api.detailAssist(id).then(res => {
        if(res.ok)
            dispatch(getRepairDetailSuccess(res.data));
        else
            dispatch(getRepairDetailFail());
        return res.ok;
    });
};
/*=============================批量修改索赔分类================================= */
export const onClickBatch = (ids, partWarrantyCategoryId) => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const conditions = ids.map(id => {
        const {rowVersion} = data.find(item => item.id === id);
        return {
            id,
            rowVersion
        };
    });
    return api.updateBacth({
        partWarrantyCategoryId,
        data: conditions
    }).then(res => res.ok);
};
/* =======================详情页修改索赔分类================================== */
export const onClickBatchForDetail = (id, partWarrantyCategoryId) => (dispatch, getState) => {
    const {rowVersion} = getState().getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.updateBacth({
        partWarrantyCategoryId,
        data: [{
            id,
            rowVersion
        }]
    }).then(res => res.ok);
};

/*==============================清除数据================================= */
export const CLEAR_DATA = 'CLEAR_DATA';
export const clearData = () => ({
    type: CLEAR_DATA
});

export const CHANGE_BATCH = 'CHANGE_BATCH';
export const changeBatch = () => ({
    type: CHANGE_BATCH
});

export const DELETE_DETAIL = 'DELETE_DETAIL';
export const deleteDetail = id => ({
    type: DELETE_DETAIL,
    id,
});

export const DELETE_ALL_DETAIL = 'DELETE_ALL_DETAIL';
export const deleteAllDetail = () => ({
    type: DELETE_ALL_DETAIL,
});
export const SELECT_DATA = 'SELECT_DATA';
export const selectData = (record = {}) => ({
    type: SELECT_DATA,
    data: {
        partWarrantyCategoryId: record.id,
        partWarrantyCategoryCode: record.code,
        partWarrantyCategoryName: record.name,
    }
});
export const SELECT_DETAILS = 'SELECT_DETAILS';
export const selectDetails = data => ({
    type: SELECT_DETAILS,
    data: data.map(item => ({
        dutyUnitId: item.id,
        dutyUnitCode: item.code,
        dutyUnitName: item.name,
        isDefault: false,
    }))
});

export const CHANGE_DEFAULT = 'CHANGE_CAUSE';
export const changeDefault = (id, value) => ({
    type: CHANGE_DEFAULT,
    id,
    value
});


export const GET_BRANDS_BEGIN = 'GET_BRANDS_BEGIN';
export const GET_BRANDS_SUCCESS = 'GET_BRANDS_SUCCESS';
export const GET_BRANDS_FAIL = 'GET_BRANDS_FAIL';
export const getBrandBegin = () => ({
    type: GET_BRANDS_BEGIN
});
export const getBrandSuccess = data => ({
    type: GET_BRANDS_SUCCESS,
    data
});
export const getBrandFail = () => ({
    type: GET_BRANDS_FAIL,
});

export const getBrands = condition => dispatch => {
    dispatch(getBrandBegin());
    return api.getBrands(condition).then(res => {
        if(res.ok)
            dispatch(getBrandSuccess(res.data));
        else
            dispatch(getBrandFail());
        return res.ok;
    });
};

export const getEditInit = id => dispatch => Promise.all([dispatch(getBrands()), dispatch(getDetail(id, true))]).then(values => values[0] && values[1]);

//价格操作
export const DELETE_PRICE = 'DELETE_PRICE';
export const deletePriceDetail = id => ({
    type: DELETE_PRICE,
    id,
});

export const DELETE_ALL_PRICE = 'DELETE_ALL_PRICE';
export const deleteAllPrice = () => ({
    type: DELETE_ALL_PRICE,
});

export const ADD_PRICE = 'ADD_PRICE';
export const addPrice = () => ({
    type: ADD_PRICE,
    data: {
        id: uuid(),
        year: moment().format('YYYY'),
        month: moment().format('M'),
        price: 0,
        priceType: partsPriceType.一般ZFOB,
    }
});

export const UPDATE_PRICE = 'UPDATE_PRICE';
export const updatePrice = data => ({
    type: UPDATE_PRICE,
    data,
});

//品牌操作
export const DELETE_BRAND = 'DELETE_BRAND';
export const deleteBrandDetail = id => ({
    type: DELETE_BRAND,
    id,
});

export const DELETE_ALL_BRAND = 'DELETE_ALL_BRAND';
export const deleteAllBrand = () => ({
    type: DELETE_ALL_BRAND,
});

export const ADD_BRAND = 'ADD_BRAND';
export const addBrand = () => ({
    type: ADD_BRAND,
    data: {
        id: uuid()
    }
});

export const UPDATE_BRAND = 'UPDATE_BRAND';
export const updateBrand = data => ({
    type: UPDATE_BRAND,
    data,
});

export const onSubmitUserDefinedAssistParts = (data, details) => () => {
    const addCondition = {
        code: data.code,
        name: data.name,
        description: data.description,
        details: details.map(o => ({
            claimPrice: o.claimPrice,
            dealerId: o.dealerId,
            productCategoryId: o.productCategoryId,
            engineCode: o.engineCode,
            transmissionSn: o.transmissionSn,
            singleQty: o.singleQty,
            maxQty: o.maxQty,
            minQty: o.minQty,
            unit: o.unit,
            currency: o.currency,
        }))
    };
    const updateCondition = {
        name: data.name,
        description: data.description,
        details: details.map(o => ({
            claimPrice: o.claimPrice,
            dealerId: o.dealerId,
            productCategoryId: o.productCategoryId,
            engineCode: o.engineCode,
            transmissionSn: o.transmissionSn,
            singleQty: o.singleQty,
            maxQty: o.maxQty,
            minQty: o.minQty,
            unit: o.unit,
            currency: o.currency,
        })),
        rowVersion: data.rowVersion
    };
    return data.id ? api.updateAssist(data.id, updateCondition)
        .then(res => ({success: res.ok})) : api.addAssist(addCondition)
        .then(res => ({success: res.ok}));
};

//更多 MORE_BRAND
export const MORE_ADD_BRAND = 'MORE_ADD_BRAND';
export const moreAddBrand = data => ({
    type: MORE_ADD_BRAND,
    data
});
export const MORE_DELETE_BRAND = 'MORE_DELETE_BRAND';
export const moreDeleteBrand = data => ({
    type: MORE_DELETE_BRAND,
    data
});
export const moreDetail = () => (dispatch, getState) => {
    const {tempPartServiceProperties = []} = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    dispatch(moreAddBrand(tempPartServiceProperties.slice(0, 10)));
    dispatch(moreDeleteBrand(tempPartServiceProperties.slice(10)));
};
